# -*- coding: UTF-8 -*-
__license__ = "GPL http://www.gnu.org/licenses/gpl.txt"
__author__="xushengs@gmail.com"
__homepage__ = "http://fdream.net"
__date__ ="2010-2-26 17:39:27"
__version = "0.1"

import logging

from google.appengine.api import urlfetch

class Response(object):
    def __init__(self, status_code, headers):
        self.status_code = status_code
        self.headers = headers

class rest:
    @classmethod
    def get(self, url, body=None, headers={}, allow_truncated=False, follow_redirects=True, deadline=None):
        return self.__request(url, method='GET', body=body, headers=headers, allow_truncated=allow_truncated, follow_redirects=follow_redirects, deadline=deadline)

    @classmethod
    def post(self, url, body=None, headers={}, allow_truncated=False, follow_redirects=True, deadline=None):
        return self.__request(url, method='POST', body=body, headers=headers, allow_truncated=allow_truncated, follow_redirects=follow_redirects, deadline=deadline)

    @classmethod
    def put(self, url, body=None, headers={}, allow_truncated=False, follow_redirects=True, deadline=None):
        return self.__request(url, method='PUT', body=body, headers=headers, allow_truncated=allow_truncated, follow_redirects=follow_redirects, deadline=deadline)

    @classmethod
    def delete(self, url, body=None, headers={}, allow_truncated=False, follow_redirects=True, deadline=None):
        return self.__request(url, method='DELETE', body=body, headers=headers, allow_truncated=allow_truncated, follow_redirects=follow_redirects, deadline=deadline)

    @classmethod
    def head(self, url, body=None, headers={}, allow_truncated=False, follow_redirects=True, deadline=None):
        return self.__request(url, method='HEAD', body=body, headers=headers, allow_truncated=allow_truncated, follow_redirects=follow_redirects, deadline=deadline)

    @classmethod
    def __request(self, url, method='GET', body=None, headers={}, allow_truncated=False, follow_redirects=True, deadline=None):
        try:
            return urlfetch.fetch(url=url, method=method, payload=body, headers=headers, allow_truncated=allow_truncated, follow_redirects=follow_redirects, deadline=deadline)
        except urlfetch.Error:
            logging.error('urlfetch exception happend!')            
            return Response(0, {'error': 'urlfetch error'})
